"""
角色 CRUD 操作
"""
from typing import Optional, List
from tortoise.exceptions import DoesNotExist, IntegrityError
from ..models.role import Role
from ..schemas.role import RoleCreate, RoleUpdate
from ..core.exceptions import UserNotFoundError


class RoleCRUD:
    """角色 CRUD 操作类"""

    @staticmethod
    async def create_role(role_data: RoleCreate) -> Role:
        """创建角色"""
        try:
            role = await Role.create(
                role_id=role_data.role_id,
                role_name=role_data.role_name
            )
            return role
        except IntegrityError:
            raise ValueError("角色ID或角色名称已存在")

    @staticmethod
    async def get_role_by_id(role_id: str) -> Role:
        """根据 role_id 获取角色"""
        try:
            role = await Role.get(role_id=role_id)
            return role
        except DoesNotExist:
            raise UserNotFoundError(f"角色ID {role_id} 不存在")

    @staticmethod
    async def get_role_by_pk(pk_id: int) -> Role:
        """根据主键ID获取角色"""
        try:
            role = await Role.get(id=pk_id)
            return role
        except DoesNotExist:
            raise UserNotFoundError(f"角色 {pk_id} 不存在")

    @staticmethod
    async def get_role_by_name(role_name: str) -> Optional[Role]:
        """根据角色名称获取角色"""
        return await Role.filter(role_name=role_name).first()

    @staticmethod
    async def get_roles(skip: int = 0, limit: int = 100) -> List[Role]:
        """获取角色列表"""
        return await Role.all().offset(skip).limit(limit)

    @staticmethod
    async def get_roles_count() -> int:
        """获取角色总数"""
        return await Role.all().count()

    @staticmethod
    async def update_role(role_id: str, role_data: RoleUpdate) -> Role:
        """更新角色信息"""
        role = await RoleCRUD.get_role_by_id(role_id=role_id)
        
        update_data = role_data.model_dump(exclude_unset=True)
        if update_data:
            try:
                await role.update_from_dict(update_data)
                await role.save()
            except IntegrityError:
                raise ValueError("角色名称已存在")
        
        return role

    @staticmethod
    async def delete_role(role_id: str) -> bool:
        """删除角色"""
        role = await RoleCRUD.get_role_by_id(role_id=role_id)
        await role.delete()
        return True

    @staticmethod
    async def role_exists(role_id: str) -> bool:
        """检查角色是否存在"""
        return await Role.filter(role_id=role_id).exists()


# 创建全局实例
role_crud = RoleCRUD()